package com.example.homework.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.homework.App
import com.example.homework.R
import com.example.homework.adapters.PhotosRecyclerViewAdapter
import com.example.homework.databinding.FragmentGalleryBinding
import com.example.homework.repositories.PhotoRepository
import com.example.homework.viewmodels.PhotoViewModel
import com.example.homework.viewmodels.PhotoViewModelFactory
import kotlinx.coroutines.launch

class GalleryFragment : Fragment() {
    private val viewModel: PhotoViewModel by activityViewModels<PhotoViewModel>() {
        PhotoViewModelFactory(PhotoRepository((requireActivity().application as App).db.photoDao()))
    }
    private var _binding: FragmentGalleryBinding? = null
    private val binding: FragmentGalleryBinding
        get() = _binding!!

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentGalleryBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val photoAdapter: PhotosRecyclerViewAdapter = PhotosRecyclerViewAdapter()
        binding.photosRecyclerView.adapter = photoAdapter
        binding.showCameraFragmentButton.setOnClickListener {
            findNavController().navigate(R.id.action_galleryFragment_to_cameraFragment)
        }
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.photos.collect {
                photoAdapter.submitList(it)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}